#include "command.h"

#define INDENT_1 "|-- "
#define INDENT_2 "|   "

void draw_indent(int indent_level)
{
	if (indent_level == 0) return;

	for (int i = 0; i < indent_level - 1; i++)
		printf(INDENT_2);
	printf(INDENT_1);
}

int draw_one_dir_tree(int dir_indent_level, const char *dir)
{
	int file_indent_level = dir_indent_level + 1;

	// directory
	draw_indent(dir_indent_level);

	const char *last_slash = strrchr(dir, '/');	
	const char *relative_dir;

	if (last_slash == NULL) {
		printf("%s%s%s\n", DIR_STYLE, dir, RESET);
	} else {
		relative_dir = last_slash + 1;
		printf("%s%s%s\n", DIR_STYLE, relative_dir, RESET);
	}

	// file
	DIR *directory = opendir(dir);
	if (directory == NULL) {
		fprintf(stderr, "tree error: draw_one_dir_tree-->opendir\n");
		return 1;
	}

	struct dirent *entry;
	while ((entry = readdir(directory)) != NULL) {
		// skip the hidden file or dir, especially .git
		if (entry->d_name[0] == '.')
			continue;

		// printf("here\n");
		char path[FILEPATH_SIZE];
		snprintf(path, sizeof(path), "%s/%s", dir, entry->d_name);
		if (is_dir(path) == 1) {
			draw_one_dir_tree(dir_indent_level + 1, path);
		} else {
			draw_indent(file_indent_level);
			printf("%s\n", entry->d_name);
		}
	}

	closedir(directory);

	return 0;
}

int _tree(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 2) {
		fprintf(stderr, "Usage: tree [dir]\n");
		return -1;
	}

	// determine the directory
	const char *dir = (argc == 2) ? argv[1] : ".";
	if (is_dir(dir) != 1) {
		fprintf(stderr, "Usage: tree [dir]\n");
		return -1;
	}

	// draw the directory tree
	int status = 0;
	status = draw_one_dir_tree(0, dir);

	return status;
}
